package com.lanou.zakerproject.community;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.lanou.zakerproject.R;
import com.lanou.zakerproject.base.VolleySingleton;
import com.lanou.zakerproject.tool.GsonRequest;


/**
 * Created by dllo on 16/1/13.
 */
public class ConcernFragment extends Fragment {
    private ListView mListView;
    private Context context;
    private myAdapter adapter;
    private int currentIndex = -1;
    MediaController mMediaCtrl;
    private int playPosition = -1;
    private boolean isPaused = false;
    private boolean isPlaying = false;
    private VideoView mVideoView;
    private String url = "http://c.3g.163.com/nc/video/home/0-10.html";

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_concern, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mListView = (ListView) view.findViewById(R.id.community_listView_concern);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getRequsetData(url);
        mListView.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub

            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                if ((currentIndex < firstVisibleItem || currentIndex > mListView.getLastVisiblePosition()) && isPlaying) {
                    System.out.println("滑动的：" + mVideoView.toString());
                    playPosition = mVideoView.getCurrentPosition();
                    mVideoView.pause();
                    mVideoView.setMediaController(null);
                    isPaused = true;
                    isPlaying = false;
                    System.out.println("视频已经暂停：" + playPosition);
                }
            }
        });
    }


    class myAdapter extends BaseAdapter {
        private Context context;
        private VideoData videoData;

        public myAdapter(Context context, VideoData videoData) {
            this.context = context;
            this.videoData = videoData;
        }

        @Override
        public int getCount() {
            return videoData.getVideoList().size();
        }

        @Override
        public Object getItem(int position) {
            return videoData.getVideoList().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            final int mPosition = position;
            if (convertView == null) {
                Log.d("1",convertView+"convertView==null");
                convertView = LayoutInflater.from(context).inflate(R.layout.item_video_layout, null);
                holder = new ViewHolder();
                holder.videoImage = (ImageView) convertView.findViewById(R.id.video_image);
                holder.videoNameText = (TextView) convertView.findViewById(R.id.video_name_text);
                holder.videoPlayBtn = (ImageButton) convertView.findViewById(R.id.video_play_btn);
                holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.progressbar);
                convertView.setTag(holder);
            } else {
                Log.d("2",convertView+"convertView!=null");
                holder = (ViewHolder) convertView.getTag();
            }
            ImageLoader.ImageListener listener = ImageLoader.getImageListener(holder.videoImage, R.mipmap.ae, R.mipmap.default_img_nonet);
            VolleySingleton.getImageLoader().get(videoData.getVideoList().get(position).getCover(), listener);
            holder.videoNameText.setText(videoData.getVideoList().get(position).getTitle());
            holder.videoPlayBtn.setVisibility(View.VISIBLE);
            holder.videoImage.setVisibility(View.VISIBLE);
            holder.videoNameText.setVisibility(View.VISIBLE);
            mMediaCtrl = new MediaController(context, false);
            if (currentIndex == position) {
                Log.d("3",currentIndex+"currentIndex == position");
                holder.videoPlayBtn.setVisibility(View.INVISIBLE);
                holder.videoImage.setVisibility(View.INVISIBLE);
                holder.videoNameText.setVisibility(View.INVISIBLE);
                if (isPlaying || playPosition == -1) {
                    if (mVideoView != null) {
                        Log.d("4",mVideoView+"mVideoView!=null");
                        mVideoView.setVisibility(View.GONE);
                        mVideoView.stopPlayback();
                        holder.mProgressBar.setVisibility(View.GONE);
                    }
                }
                mVideoView = (VideoView) convertView.findViewById(R.id.videoview);
                mVideoView.setVisibility(View.VISIBLE);
                mMediaCtrl.setAnchorView(mVideoView);
                mMediaCtrl.setMediaPlayer(mVideoView);
                mVideoView.setMediaController(mMediaCtrl);
                mVideoView.requestFocus();
                holder.mProgressBar.setVisibility(View.VISIBLE);
                if (playPosition > 0 && isPaused) {
                    mVideoView.start();
                    isPaused = false;
                    isPlaying = true;
                    holder.mProgressBar.setVisibility(View.GONE);
                } else {
                    mVideoView.setVideoPath(videoData.getVideoList().get(position).getMp4_url());
                    Log.d("myAdapter----->", videoData.getVideoList().get(position).getMp4_url());
                    isPaused = false;
                    isPlaying = true;
                }
//视频或者音频到结尾时触发的方法
                mVideoView.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if (mVideoView != null) {
                            mVideoView.seekTo(0);//定位，设置播放位置
                            mVideoView.stopPlayback();
                            currentIndex = -1;
                            isPaused = false;
                            isPlaying = false;
                            holder.mProgressBar.setVisibility(View.GONE);
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
                mVideoView.setOnPreparedListener(new OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        holder.mProgressBar.setVisibility(View.GONE);
                        mVideoView.start();
                    }
                });
            } else {
                holder.videoPlayBtn.setVisibility(View.VISIBLE);
                holder.videoImage.setVisibility(View.VISIBLE);
                holder.videoNameText.setVisibility(View.VISIBLE);
                holder.mProgressBar.setVisibility(View.GONE);
            }

            holder.videoPlayBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    currentIndex = mPosition;
                    playPosition = -1;
                    adapter.notifyDataSetChanged();
                }
            });
            return convertView;
        }

    }

    class ViewHolder {
        ImageView videoImage;
        TextView videoNameText;
        ImageButton videoPlayBtn;
        ProgressBar mProgressBar;
    }

    private void getRequsetData(String urls) {
        GsonRequest<VideoData> gsonRequest = new GsonRequest<>(urls, VideoData.class, new Response.Listener<VideoData>() {
            @Override
            public void onResponse(VideoData response) {
                adapter = new myAdapter(context, response);
                mListView.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        VolleySingleton.getInstance()._addRequest(gsonRequest);
    }


}
